package com.rainbowBoot.config;

import com.rainbowBoot.utils.SingleCacheUtil;
import com.rainbowBoot.utils.TaskUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域过滤器
 */
@Component
@WebFilter(filterName = "allFilter",urlPatterns = "/*")
public class Config implements Filter {

    private Logger logger = LogManager.getLogger(Config.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        /*logger.info("启动定时任务");
        task();*/
        /*logger.info("加载缓存");
        cache();*/
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        /*logger.info("正在对请求进行跨域处理");
        // 解决跨域问题和乱码问题
        crossDomain(response);*/
        // 禁止frame嵌入
        response.addHeader("x-frame-options","SAMEORIGIN");

        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    /**
     * 处理全局跨域问题和乱码问题
     * @param response
     */
    private void crossDomain(HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin","*");
    }

    /**
     * 执行定时任务
     */
    private void task() {
        logger.info("正在启动定时任务...");
        TaskUtil taskUtil = new TaskUtil();
    }

    /**
     * 加载缓存
     */
    private void cache() {
        logger.info("正在加载缓存...");
        SingleCacheUtil singleCacheUtil = SingleCacheUtil.getSingleCacheUtil();
        singleCacheUtil.setCache("test",null);
    }

}
